package com.atguigu.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet(
        urlPatterns = {"/servlet2"},
        initParams = {
                @WebInitParam(name = "key2a", value = "value2a"),
                @WebInitParam(name = "key2b", value = "value2b")
        }
)
public class Servlet2 extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletConfig servletConfig = getServletConfig();

        //获取初始配置信息
        //根据参数名获取参数值
        String key2b = servletConfig.getInitParameter("key2b");

        System.out.println("key2b : " + key2b);


        System.out.println("--------------servletContext----------------------");

        //第一种方式
        ServletContext servletContext = getServletContext();
        //第二种方式
        ServletContext servletContext1 = servletConfig.getServletContext();

        //第三种方式
        ServletContext servletContext2 = req.getServletContext();

        //获取所有参数名
        //hasMoreElements 判断是否还有元素
        //nextElement 获取下一个元素
        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();

        while (initParameterNames.hasMoreElements()) {
            String panme = initParameterNames.nextElement();
            System.out.println("pname : " + panme);
        }

        //获取域对象
        String ka = (String) servletContext.getAttribute("ka");
        System.out.println("ka : " + ka);
    }
}
